<?php
/**
 * Mysql数据库驱动类
 */
class MysqlDb extends DbHelper
{

    /**
     * 架构函数 读取数据库配置信息
     * @access public
     * @param array $config 数据库配置数组
     */
    public function __construct($config='')
    {
        !extension_loaded('mysql') && Yucy::getInstance()->getHelper()->throwException('NOT_SUPPERT:mysql');
        
        !empty($config) && $this->config = $config;
    }

    /**
     * 连接数据库方法
     * @access public
     * @param array $config
     * @param integer $linkId
     * @return object
     */
    public function connect($config, $linkId = 0)
    {
        if (isset($this->linkId[$linkId]))  return $this->linkId[$linkId];
        
        // 处理不带端口号的socket连接情况
        $host = $config['hostname'].($config['hostport'] ? ":{$config['hostport']}" : '');
        
        $clientflag = isset($config['clientflag']) ? $config['clientflag'] : null;
        
        // 连接数据库服务器
        $this->linkId[$linkId] = $this->pconnect ? mysql_pconnect($host, $config['username'], $config['password']) : mysql_connect($host, $config['username'], $config['password'], $clientflag);
        
        // 连接到数据库
        if (!$this->linkId[$linkId] || (!empty($config['database']) && !mysql_select_db($config['database'], $this->linkId[$linkId])))
        {
            Yucy::getInstance()->getHelper()->throwException(mysql_error());
        }
        
        $db_version = mysql_get_server_info($this->linkId[$linkId]);
        
        //使用UTF8存取数据库 需要mysql 4.1.0以上支持
        if ($db_version >= "4.1")  mysql_query("SET NAMES '".$config['charset']."'", $this->linkId[$linkId]);
        
        //设置 sql_model
        if($db_version >'5.0.1') mysql_query("SET sql_mode=''",$this->linkId[$linkId]);

        // 标记连接成功
        $this->connected = true;
        
        
        return $this->linkId[$linkId];
    }
    

    /**
     * 释放查询结果
     * @access public
     */
    public function free() 
    {
        @mysql_free_result($this->queryId);
        $this->queryId = 0;
    }
    

    /**
     * 执行查询 返回数据集
     * @access public
     * @param string $str  sql指令
     * @return mixed
     */
    public function query($str)
    {
        $this->initConnect(false);
        if (!$this->currentLinkId) return false;
        
        $this->strQuery = $str;
        //释放前次的查询结果
        if ($this->queryId) $this->free();
        
        $this->Q(1);
        $this->queryId = mysql_query($str, $this->currentLinkId);
        
        $this->debug();
        if (false === $this->queryId) Yucy::getInstance()->getHelper()->throwException($this->error());

        $this->affectRows = mysql_num_rows($this->queryId);
        return $this->_getAll();
    }
    
    
    /**
     * 获得所有的查询数据
     * @access private
     * @return array
     */
    private function _getAll() 
    {
        //返回数据集
        $result = array();
        if($this->affectRows >0) 
        {
            while($row = mysql_fetch_assoc($this->queryId))
            {
                $result[] = $row;
            }
            mysql_data_seek($this->queryId, 0);
        }
        return $result;
    }
    

    /**
     * 执行语句
     * @access public
     * @param string $str  sql指令
     * @return integer
     */
    public function execute($str)
    {
        $this->initConnect(true);
        if (!$this->currentLinkId) return false;
        $this->strQuery = $str;
        
        //释放前次的查询结果
        if ($this->queryId) $this->free();
        
        $this->W(1);
        $result = mysql_query($str, $this->currentLinkId);
        
        $this->debug();
        if ( false === $result) Yucy::getInstance()->getHelper()->throwException($this->error());

        $this->affectRows = mysql_affected_rows($this->currentLinkId);
        $this->lastInsId = mysql_insert_id($this->currentLinkId);
        return $this->affectRows;
    }

    /**
     * 启动事务
     * @access public
     * @return void
     */
    public function startTrans() 
    {
        $this->initConnect(true);
        if (!$this->currentLinkId) return false;
        
        if ($this->transTimes == 0) 
        {
            mysql_query('START TRANSACTION', $this->currentLinkId);
        }
        $this->transTimes++;
        return ;
    }

    /**
     * 提交状态下面的查询提交
     * @access public
     * @return boolen
     * @throws Execption
     */
    public function commit()
    {
        if ($this->transTimes > 0)
        {
            $result = mysql_query('COMMIT', $this->currentLinkId);
            $this->transTimes = 0;
            if(!$result) Yucy::getInstance()->getHelper()->throwException($this->error());
            
        }
        return true;
    }

    /**
     * 事务回滚
     * @access public
     * @return boolen
     */
    public function rollback()
    {
        if ($this->transTimes > 0)
        {
            $result = mysql_query('ROLLBACK', $this->currentLinkId);
            $this->transTimes = 0;
            if(!$result) Yucy::getInstance()->getHelper()->throwException($this->error());
            
        }
        return true;
    }


    /**
     * 替换记录
     * @return false | int
     */
    public function replace() 
    {
    	// 分析表达式
        $options =  $this->parseOptions();
        if (empty($options)) return false;
        
        $data = $this->getData();
        if (!count($data)) return false;
        foreach ($data as $key=>$val)
        {
            $value = $this->parseValue($val['value']);
            // 过滤非标量数据
            if(is_scalar($value)) 
            { 
                $values[] = $value;
                $fields[] = $this->addSpecialChar($key);
            }
        }
        $sql = 'REPLACE INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')';
        return $this->execute($sql);
    }

    
    /**
     * 插入记录
     * @return false | int
     */
    public function insert()
	{
		$data = $this->getData();
		if (empty($data)) return false;
			
        // 分析表达式
        $options =  $this->parseOptions();
        if (empty($options)) return false;

        foreach ($data as $key=>$val)
		{
            $value = $this->parseValue($val['value']);
            if (is_scalar($value)) // 过滤非标量数据
			{
                $values[] = $value;
                $fields[] = $this->addSpecialChar($key);
            }
        }
        $sql = 'INSERT INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')';
        $sql .= $this->parseLock(isset($options['lock']) ? $options['lock'] : false);
        return $this->execute($sql);
    }
    

    /**
     * 更新记录
     * @return false | int
     */
    public function update()
	{
		$data = $this->getData();
		if (empty($data)) return false;

        // 分析表达式
        $options =  $this->parseOptions();
        
        $sql = 'UPDATE '
            .$this->parseTable($options['table'])
            .$this->parseSet($data)
            .$this->parseWhere(isset($options['where'])?$options['where']:'')
            .$this->parseOrder(isset($options['order'])?$options['order']:'')
            .$this->parseLimit(isset($options['limit'])?$options['limit']:'')
            .$this->parseLock(isset($options['lock'])?$options['lock']:false);
        return $this->execute($sql);
    }
    

    /**
     * 删除记录
     * @return false | integer
     */
    public function delete()
    {
        // 分析表达式
        $options =  $this->parseOptions();
        if (empty($options)) return false;

        $sql = 'DELETE FROM '
            .$this->parseTable($options['table'])
            .$this->parseWhere(isset($options['where'])?$options['where']:'')
            .$this->parseOrder(isset($options['order'])?$options['order']:'')
            .$this->parseLimit(isset($options['limit'])?$options['limit']:'')
            .$this->parseLock(isset($options['lock'])?$options['lock']:false);
        return $this->execute($sql);
    }

    /**
     * 查找记录
     * @access public
     * @return array|null
     */
    public function select()
	{
        // 分析表达式
        $options =  $this->parseOptions();

        $sql   = str_replace(
            array('%TABLE%','%DISTINCT%','%FIELDS%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%'),
            array(
                $this->parseTable($options['table']),
                $this->parseDistinct(isset($options['distinct']) ? $options['distinct'] : false),
                $this->parseField(isset($options['field']) ? $options['field'] : ''),
                $this->parseJoin(isset($options['join']) ? $options['join'] : ''),
                $this->parseWhere(isset($options['where']) ? $options['where'] : ''),
                $this->parseGroup(isset($options['group']) ? $options['group'] : ''),
                $this->parseHaving(isset($options['having']) ? $options['having'] : ''),
                $this->parseOrder(isset($options['order']) ? $options['order'] : ''),
                $this->parseLimit(isset($options['limit']) ? $options['limit'] : '')
            ), $this->selectSql);
        $sql .= $this->parseLock(isset($options['lock']) ? $options['lock']:false);//print_r($sql);exit;
        $result = $this->query($sql);

        if (empty($result)) return array();
		
        return $result;
    }
    
    
    /**
     * 获取单条数据
     *
     * @return Array
     */
    public function getRow()
    {
    	$result = $this->limit(1)->select();
    	return (!empty($result) && isset($result['0'])) ? $result['0'] : array();
    }
    
    
    /**
     * 
     * 获取某个字段的值
     */
    public function getValue($field)
    {
    	$result = $this->getRow();
    	return isset($result[$field]) ? $result[$field] : NULL;
    }
    

    /**
     * 关闭数据库
     * @access public
     */
    public function close()
    {
        if (!empty($this->queryId))　mysql_free_result($this->queryId);
        
        if ($this->linkId && !mysql_close($this->currentLinkId)) if(!$result) Yucy::getInstance()->getHelper()->throwException($this->error());

        $this->currentLinkId = 0;
    }
    

    /**
     * 数据库错误信息
     * 并显示当前的SQL语句
     * @access public
     * @return string
     */
    public function getError()
    {
        $this->error = mysql_error($this->currentLinkId);
        
        if($this->debug && '' != $this->strQuery)
        {
            $this->error .= "\n [ SQL语句 ] : ".$this->strQuery;
        }
        
        return $this->error;
    }

    /**
     * SQL指令安全过滤
     * @access public
     * @param string $str  SQL字符串
     * @return string
     */
    public function escape_string($str)
    {
        return mysql_escape_string($str);
    }

}
?>